package cn.lanqiao.rabc.controller;

import cn.lanqiao.rabc.entity.User;
import cn.lanqiao.rabc.service.UserService;
import cn.lanqiao.rabc.util.CurrentUserUtil;
import cn.lanqiao.rabc.util.MD5Util;
import cn.lanqiao.rabc.util.Result;
import cn.lanqiao.rabc.vo.QueryUserVO;
import cn.lanqiao.rabc.vo.UserVO;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

import static cn.lanqiao.rabc.util.Result.fail;
import static cn.lanqiao.rabc.util.Result.success;


@Log4j2
@Api(tags = "用户管理功能")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Value("${cn.lanqiao.key}")
    private String key;

    @ApiOperation("分页获得用户列表")
    @PostMapping("/query")
    public ResponseEntity query(@RequestBody QueryUserVO queryUserVO) {
        PageHelper.startPage(queryUserVO.getPageNum(), queryUserVO.getPageSize());
        List<UserVO> userList = userService.query(queryUserVO);
        PageInfo<UserVO> pageInfo = new PageInfo<>(userList);
        return success(pageInfo);
    }

    @ApiOperation("通过UserId获得指定用户")
    @GetMapping("/{id}")
    public ResponseEntity queryByUserIdUser(@PathVariable("id") int userId) {
        return success(userService.queryByUserIdUser(userId));
    }

    @ApiOperation("注册用户")
    @PostMapping("/insertOrUpdate")
    public ResponseEntity insert(@Valid @RequestBody UserVO userVO) {
        log.info(userVO);
        if (userVO.getUserId() != null && userVO.getUserId() != 0) {
            userService.update(userVO);
        } else {
            userVO.setPassword(BCrypt.hashpw(userVO.getPassword(), BCrypt.gensalt()));
            userService.insert(userVO);
        }
        return success();
    }

    @ApiOperation("上传头像")
    @PostMapping("/upload")
    public ResponseEntity upload(MultipartFile file) {
        return success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody UserVO user) {
        //调用service
        UserVO userVO = userService.checkUser(user);
        if (userVO != null) {
            if (BCrypt.checkpw(user.getPassword(), userVO.getPassword())) {
                //生成token
                String token = JWT.create()
                        .withClaim("userId", userVO.getUserId())//jwt中存用户id
                        .withClaim("userName", userVO.getUserName())//jwt中存用户名
                        .withClaim("roleId", userVO.getRoleId())//角色id
                        .withClaim("roleName", userVO.getRoleName())//角色名
                        .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60))//设置失效时间一小时
                        .sign(Algorithm.HMAC256(key));//设置秘钥。
                return success(token);
            } else {
                return fail(602, "密码错误！");
            }
        } else {
            return fail(601, "用户名不存在！");
        }
    }

    @ApiOperation("删除用户")
    @PostMapping("/delete/{ids}")
    public ResponseEntity delete(@PathVariable String ids) {
        userService.delete(ids);
        return success();
    }

    @ApiOperation("获得登录用户的信息")
    @GetMapping("/getUserByToken")
    public ResponseEntity getUserByToken() {
        return success(CurrentUserUtil.get());
    }

}
